# py_to_mp.py
import importlib.util
import msgpack
import os

def convert_py_to_mp(py_file):
    """将 .py 文件转换为 .mp 文件"""
    mp_file = py_file.replace(".py", ".mp")

    try:
        # 导入 .py 文件
        spec = importlib.util.spec_from_file_location("config", py_file)
        if spec is None:
            print(f"Error: Could not find module spec for {py_file}")
            return False

        module = importlib.util.module_from_spec(spec)
        if module is None:
             print(f"Error: Could not create module from spec for {py_file}")
             return False
        spec.loader.exec_module(module)

        # 提取配置字典
        config_data = getattr(module, "config", {})  # 假设配置字典名为 "config"

        # 序列化为 MessagePack 格式
        packed_config = msgpack.packb(config_data)

        # 保存到 .mp 文件
        with open(mp_file, "wb") as f:
            f.write(packed_config)
        return True

    except Exception as e:
        print(f"Error converting {py_file} to {mp_file}: {e}")
        return False

def load_config_from_mp(mp_file):
    """从 .mp 文件加载配置"""
    try:
        with open(mp_file, "rb") as f:
            packed_config = f.read()
        config_data = msgpack.unpackb(packed_config, raw=False)
        return config_data
    except Exception as e:
        print(f"Error loading config from {mp_file}: {e}")
        return None

def main():
    # 创建配置目录（如果不存在）
    config_dir = "configs"
    if not os.path.exists(config_dir):
        os.makedirs(config_dir)

    # 扫描配置目录
    for filename in os.listdir(config_dir):
        if filename.endswith(".py"):
            py_file = os.path.join(config_dir, filename)
            if convert_py_to_mp(py_file):
                print(f"Successfully converted {py_file} to {py_file.replace('.py', '.mp')}")
            else:
                print(f"Failed to convert {py_file}")

    # 加载其他插件
    # ...

    # 示例：加载一个插件的配置
    config_data = load_config_from_mp(os.path.join(config_dir, "my_plugin.mp"))
    if config_data:
        print("My Plugin Config:", config_data)
    else:
        print("Failed to load my_plugin.mp")

if __name__ == "__main__":
    main()
